package hotel.switchs.oversea.biz.service.impl;

import com.alibaba.fastjson.JSONObject;
import hotel.base.oversea.constant.CommonConstants;
import hotel.base.oversea.constant.SwitchConstants;
import hotel.base.oversea.service.impl.BaseServiceImpl;
import hotel.base.oversea.utils.JacksonUtil;
import hotel.base.oversea.utils.Result;
import hotel.base.oversea.vo.ResultStatusInfoVo;
import hotel.switchs.oversea.api.VO.CityInfoVo;
import hotel.switchs.oversea.api.VO.PagingInfoVo;
import hotel.switchs.oversea.api.VO.SwitchCityInfoVo;
import hotel.switchs.oversea.api.entity.SwitchCityInfo;
import hotel.switchs.oversea.biz.config.service.RedisService;
import hotel.switchs.oversea.biz.mapper.SwitchCityInfoMapper;
import hotel.switchs.oversea.biz.service.SwitchCityInfoService;
import hotel.switchs.oversea.biz.utils.SwitchsHttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @Author lmf
 * @Date 2020/5/13 15:23
 **/
@Service
public class SwitchCityInfoServiceImpl extends BaseServiceImpl<SwitchCityInfoVo> implements SwitchCityInfoService {

    @Value("${profile.type}")
    private String profile;

    @Autowired
    private SwitchCityInfoMapper switchCityInfoMapper;

    @Autowired
    private RedisService redisService;

    /**
     * 获取城市列表
     * countryID 国家id
     * pageSize 每页数据
     * currentPageIndex 当前页
     * @return
     */
    @Retryable(value = Exception.class,maxAttempts = 4,backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public Result<Object> getcitylist(int countryID, int pageSize, int currentPageIndex)  {
        Map<String, Object> data = new HashMap<>();
        Map<String,Object> searchCandidate=new HashMap<>();
        Map<String,Object> pagingSettings=new HashMap<>();
        pagingSettings.put("pageSize",pageSize);
        pagingSettings.put("currentPageIndex",currentPageIndex);
        searchCandidate.put("countryID",countryID);
        data.put("searchCandidate",searchCandidate);
        data.put("pagingSettings",pagingSettings);
        String result= SwitchsHttpUtils.sendRequest(data,"getdltcitylist",profile);
        //对结构进行格式化
        JSONObject jsonObject = JSONObject.parseObject(result);
        ResultStatusInfoVo resultStatusInfoVo= JacksonUtil.parse(jsonObject.getString("resultStatus"),ResultStatusInfoVo.class);
        //说明调用接口失败
        if(resultStatusInfoVo.getResultCode()!=0){
            return new Result<>(resultStatusInfoVo.getResultMsg(), CommonConstants.REQUEST_ERROR);
        }
        //获取城市列表对象
        JSONObject switchCityInfos=jsonObject.getJSONObject("cityInfoList");
        //说明无城市数据返回
        if(ObjectUtils.isEmpty(switchCityInfos)){
            return new Result<>();
        }
        List<SwitchCityInfoVo> switchCityInfoVos=JacksonUtil.jsonToList(switchCityInfos.getString("cityInfo"), SwitchCityInfoVo.class);

        //获取分页
        PagingInfoVo pagingInfoVo=JacksonUtil.parse(jsonObject.getString("pagingInfo"), PagingInfoVo.class);
        CityInfoVo cityInfoVo=new CityInfoVo();
        cityInfoVo.setCityInfoList(switchCityInfoVos);
        cityInfoVo.setPagingInfo(pagingInfoVo);
        return new Result<>(cityInfoVo);
    }

    @Override
    public Result<Object> saveCityInfos(Map<String,List<SwitchCityInfoVo>> switchCityInfoVosMap){
        for (Map.Entry<String,List<SwitchCityInfoVo>> entry:switchCityInfoVosMap.entrySet()) {
            List<SwitchCityInfoVo> switchCityInfoVos = entry.getValue();
            //封装城市数据表单
            StringBuilder sb = new StringBuilder();
            List<SwitchCityInfo> switchCityInfoList=new ArrayList<>();
            Map<String,String> cityIdsMap = new HashMap<>();
             for (int i = 0; i < switchCityInfoVos.size(); i++) {
                SwitchCityInfoVo switchCityInfoVo = switchCityInfoVos.get(i);
                SwitchCityInfo switchCityInfoEntity=new SwitchCityInfo();
                switchCityInfoEntity.setCityId(switchCityInfoVo.getCityID());
                switchCityInfoEntity.setCityCode(switchCityInfoVo.getCityCode());
                switchCityInfoEntity.setCityName(switchCityInfoVo.getCityName());
                switchCityInfoEntity.setId(String.valueOf(UUID.randomUUID()));
                switchCityInfoEntity.setProvinceId(switchCityInfoVo.getProvinceID());
                switchCityInfoEntity.setProvinceName(switchCityInfoVo.getProvinceName());
                switchCityInfoEntity.setCountryId(switchCityInfoVo.getCountryID());
                switchCityInfoEntity.setCountryName(switchCityInfoVo.getCountryName());
                switchCityInfoEntity.setState(0);
                switchCityInfoEntity.setCreateTime(new Date());
                switchCityInfoEntity.setModifyTime(new Date());
                switchCityInfoList.add(switchCityInfoEntity);
                sb.append("'"+switchCityInfoEntity.getCityId()+"'");//拼接单引号,到数据库后台用in查询.
                if(i!=switchCityInfoVos.size()-1){
                    sb.append(",");
                }
                 cityIdsMap.put(String.valueOf(switchCityInfoVo.getCityID()),String.valueOf(switchCityInfoVo.getCityID()));
            }
            //旧数据删除，插入新数据
            Map idsMap = new HashMap();
            idsMap.put("ids",sb.toString());
            if(-1!=switchCityInfoMapper.deleteBatch(idsMap)){
                switchCityInfoMapper.insertList(switchCityInfoList);
            }
            //城市ID存入缓存
            Map<String,String> putMap = (Map<String,String>)redisService.get(SwitchConstants.REDIS_SWITCH_CITY_IDS);
            if(null != putMap && putMap.size()>0){
                putMap.putAll(cityIdsMap);
            }else{
                putMap=cityIdsMap;
            }
            redisService.set(SwitchConstants.REDIS_SWITCH_CITY_IDS,putMap);
        }

        return new Result<>();
    }

    @Override
    public Result<Object> queryPageCityIds(int index, int pageSize) {
        Map<String,Integer> map = new HashMap();
        map.put("index",index);
        map.put("pageSize",pageSize);
        return new Result<>(switchCityInfoMapper.queryPageDto(map));
    }

}
